﻿using CommonLibrary;
using CommonLibrary.Models;
using CommonSite.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CommonSite.Controllers
{
    [UserAuthorizeAttribute]
    public class ReceptionController : Controller
    {
        //
        // GET: /Reception/

        public ActionResult Index()
        {
            return View();
        }

        public string Query(DateTime? start, DateTime? end, int? page, int? pagesize)
        {
            start = start == null ? new DateTime(2000, 1, 1) : start.Value.Date;
            end = end == null ? DateTime.Now.Date.AddDays(1) : end.Value.Date.AddDays(1);
            if (start > end)
            {
                DateTime tmp = start.Value;
                start = end;
                end = tmp;
            }

            page = page == null ? 1 : page.Value;
            pagesize = pagesize == null ? 10 : pagesize.Value;

            using (var db = new CommonDatabase())
            {
                var seleData = "select * ";
                var cmdBody =
@"from view_flowobject 
where id in (
    select flowobjectid from wf_FlowObject_CC where 
        touser = @user and creationtime >= @p1 and
        creationtime < @p2
)";

                CommandHelper cmd = new CommandHelper(seleData, cmdBody);
                cmd.InitOrderBy(new KeyValuePair<string, bool>("id", false));
                cmd.InitPage(page.Value, pagesize.Value);

                var parms = new IDbDataParameter[] 
                {
                    db.Parameter("@user", UserAction.GetCurrentUser().UserId),
                    db.Parameter("@p1", start),
                    db.Parameter("@p2", end)
                };

                var count = cmd.ExecuteCount(db, parms);
                var data = cmd.ExecuteDatatable(db, parms);

                return JSON.ToString(new
                {
                    Total = count,
                    Rows = data
                });
            }
        }
    }
}
